<script setup>
import MwTable from "./component/MwTableHospital";
import SearchTable from "./component/SearchHospital.vue";
import MwDialog from "@/components/Dialog";
import { ElMessage, ElMessageBox } from 'element-plus';

import { CirclePlus, VideoPlay } from '@element-plus/icons-vue';
import { ref, reactive, getCurrentInstance, onMounted, watch } from "vue";

import { globalStore } from "@/store/global";
const globalVue = globalStore();

const instance = getCurrentInstance();
const _this = instance.appContext.config.globalProperties; //vue3获取当前this

// 生命周期
onMounted(() => {
  getTableData();
  getSelect();
});

const getTableData =  () => {
  // 查询医院
  let paramsHospital = {
    ...pagination,
    ...searchForm
  };
  searchForm['city'] && (paramsHospital['city'] = searchForm['city'] + '');
  tablLoading.value = true;
  instance.proxy.$http.get('overview.baseHospital',{ params: paramsHospital }).then(res=>{
    tablLoading.value = false;
    let {content, totalElements} = res.data;
    tableData.value = content;
    pagination.total = totalElements;
  }).catch(err => tablLoading.value = false);
};

let getSelect = async () => {
  selectClassification.value = await globalVue.getSelect('classificationSelect');
  instance.proxy.$http.get('archiveData.dictDetail', {params: {name: 'hospital_category'}}).then(res=>{
    selectCategory.value = res.data;
  });
  instance.proxy.$http.get('archiveData.dictDetail', {params: {name: 'hospital_scale'}}).then(res=>{
    selectScale.value = res.data;
  });
  instance.proxy.$http.get('archiveData.dictDetail', {params: {name: 'hospital_area'}}).then(res=>{
    selectArea.value = res.data;
  });
  instance.proxy.$http.get('archiveData.getCitySelect').then(res=>{
    selectCity.value = res.data.map(i => {
      i['label'] = i.selectName;
      i['value'] = i.id;
      return i;
    });
  });
};
// 下拉数据
const selectCity = ref([]);   // 城市
const selectCategory = ref([]);   // Category
const selectScale = ref([]);   // Scale
const selectArea = ref([]);   // Area
const selectClassification = ref([]);   // Number Of Passengers



// 弹框数据
let dialogShow = ref(false);
let dialogTitle = ref(' Organization');
let dialogState = ref('Add'); //  Add Edit Detail 三种状态 根据状态来判断提交方法
let dialogRef = ref(null);
let dialogFrom = reactive({
  userID: '',
  nickname: '',
  username: '',
  telephone: '',
  role: '',
});
let dialogRules = reactive({
  code: [
    { required: true, message: 'Please input Code', trigger: 'blur' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'String cannot contain spaces', trigger: 'blur' }, 
  ],
  name: [
    { required: true, message: 'Please input Name', trigger: 'blur' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'String cannot contain spaces', trigger: 'blur' }, 
  ],
  type: [
    { required: true, message: 'Please Select Classification', trigger: 'blur' },
  ],
  lng: [
    { required: true, message: 'Please input Lng', trigger: 'blur' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'String cannot contain spaces', trigger: 'blur' }, 
  ],
  lat: [
    { required: true, message: 'Please input Lat', trigger: 'blur' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'String cannot contain spaces', trigger: 'blur' }, 
  ],
  city: [
    { required: true, message: 'Please Select City', trigger: 'blur' },
  ]
});
let dialogSubmit = async () => {
  let formEl = dialogRef.value;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let url = dialogState.value == 'Add' ? 'archiveData.insertHospital' : 'archiveData.updateHospital';
      !!dialogFrom['city'] && (dialogFrom['city'] = dialogFrom['city'] + '')
      if (dialogState.value == 'Add') {
        instance.proxy.$http.post(url, dialogFrom).then(res=>{
          if (res.success) {
            onSearch();
            dialogClose();
          };
        });
      }else{
        instance.proxy.$http.put(url, dialogFrom).then(res=>{
          if (res.success) {
            onSearch();
            dialogClose();
          };
        });
      };
    } else {
      console.err('error submit!', fields);
    };
  });
};
let dialogClose = () => {
  dialogShow.value = false;
  dialogRef.value.resetFields();
  for(let item in dialogFrom){
    if(dialogFrom[item] instanceof Array){
      dialogFrom[item] = [];
    }else{
      dialogFrom[item] = '';
    };
  };
};

function openDialog(state) {
  dialogState.value = state;
  dialogShow.value = true;
  for(let item in dialogFrom){
    delete dialogFrom[item];
  };
};

// 表格数据
const tableData = ref([]);
const tablLoading = ref(false);
const pagination = reactive({
  page: 1,
  size: 10,
  total: 100
});
const searchForm = reactive({});
function onSearch(){
  getTableData();
};

function paginationChange(pagination){
  onSearch();
};

function onEdit(row){
  openDialog('Edit');
  for(let i in row) {
    if (i == 'city') {
      dialogFrom[i] = row[i].split(',');
    }else{
      dialogFrom[i] = row[i];
    }
  };
};

const onDetails = (row) => {
  _this.$router.push({path: '/hospitalDetail', query: {id: row.id}});
};
function onDelete(row){
  ElMessageBox.confirm(
    'Delete Organization ？',
    'Delete',
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel'
    }
  )
    .then(() => {
      instance.proxy.$http.delete('archiveData.deleteHospital', {data: {id: row.id + ''}}).then(res=>{
        onSearch();
        ElMessage({
          type: 'success',
          message: 'Delete Organization successfully',
        });
      });
    })
    .catch(() => {});
}

</script>
<template>
  <div class="table_index">
    <SearchTable 
      :searchForm="searchForm" 
      :selectCity="selectCity" 
      :selectCategory="selectCategory" 
      :selectScale="selectScale" 
      :selectClassification="selectClassification" 
      @onSearch="onSearch" 
      @addHospital="openDialog('Add')" />
    <div class="table_content">
      <mw-table
        v-loading="tablLoading"
        :data="tableData"
        :pagination="pagination"
        :selectCategory="selectCategory" 
        :selectClassification="selectClassification"
        @paginationChange="paginationChange"
        @operate1="onDetails"
        @operate2="onEdit"
        @operate3="onDelete"
      ></mw-table>
    </div>
  </div>

  
  <mw-dialog
    :show="dialogShow"
    :title="dialogState + dialogTitle"
    width="920px"
    @submit="dialogSubmit"
    @close="dialogClose"
  >
    <el-form ref="dialogRef" class="dialog_form" :inline="true" :model="dialogFrom" label-width="140px" :rules="dialogRules">
      <el-form-item label="Organization Code"  prop="code">
        <el-input v-model="dialogFrom.code" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Name"  prop="name">
        <el-input v-model="dialogFrom.name" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Classification"  prop="type">
        <el-select class="value_input" v-model="dialogFrom.type" placeholder="Please select" filterable clearable>
          <el-option v-for="item in selectClassification" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="City" prop="city">
        <el-select
          class="value_input" 
          v-model="dialogFrom.city"
          placeholder="Please select"
          multiple
          collapse-tags 
          collapse-tags-tooltip
          filterable
          clearable
        >
          <el-option v-for="item in selectCity" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Lng">
        <el-input type="number" v-model="dialogFrom.lng" class="value_input"  placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Lat">
        <el-input type="number" v-model="dialogFrom.lat" class="value_input"  placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Area">
        <el-input v-model="dialogFrom.area" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Manager">
        <el-input v-model="dialogFrom.manager" class="value_input"  placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Telephone">
        <el-input v-model="dialogFrom.telephone" class="value_input"  placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Address">
        <el-input v-model="dialogFrom.address" class="value_input"  placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Category">
        <el-select
          class="value_input"
          v-model="dialogFrom.category"
          placeholder="Please select"
          filterable
          clearable
        >
          <el-option v-for="item in selectCategory" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Scale">
        <el-select
          class="value_input"
          v-model="dialogFrom.scale"
          placeholder="Please select"
          filterable
          clearable
        >
          <el-option v-for="item in selectScale" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
  </mw-dialog>
</template>